import React, { useEffect, useMemo } from 'react';
import { useSelector } from 'react-redux';
import { Form, Input, InputNumber, Switch, Slider, Card, Row, Col, Typography } from 'antd';
import { selectSelectedSegment, SelectedSegmentInfo } from '@/store/selectedSegmentSlice';
import { selectMaterials } from '@/store/draftsSlice';
import '@/styles/BaseConfigForm.css';
import { RootState } from '@/store';
import { TextContent } from '@/services/meta/types';
import eventBus from '@/utils/eventBus';
import styled from 'styled-components';

const { Text } = Typography;

// 全局深色主题样式
const GlobalDarkThemeStyle = styled.div`
    .ant-form-item-label > label {
        color: #ffffff !important;
    }
    .ant-slider-rail {
        background-color: #555555 !important;
    }
    .ant-slider-track {
        background-color: #715bb8 !important;
    }
    .ant-slider-handle {
        border-color: #ffffff !important;
        background-color: #3c3c3c !important;
    }
    .ant-slider-handle:hover {
        border-color: #715bb8 !important;
    }
    .ant-slider-handle:focus {
        box-shadow: 0 0 0 5px rgba(113, 91, 184, 0.3) !important;
    }
`;

// 辅助组件：用于创建标签-滑块-数值输入的组合行
const SliderInputRow: React.FC<{
    label: string;
    name: any;
    sliderProps: any;
    inputProps: any;
}> = ({ label, name, sliderProps, inputProps }) => (
    <Form.Item>
        <Row align="middle" gutter={16}>
            <Col span={6}>
                <Text style={{ color: '#FFFFFF' }}>{label}</Text>
            </Col>
            <Col span={12}>
                <Form.Item name={name} noStyle>
                    <Slider {...sliderProps} />
                </Form.Item>
            </Col>
            <Col span={6}>
                <Form.Item name={name} noStyle>
                    <InputNumber
                        style={{
                            width: '90%',
                            background: 'linear-gradient(135deg,rgb(90, 83, 83) 0%, #1e1e1e 100%)',
                            color: '#ffffff',
                            border: '1px solid #404040',
                        }}
                        {...inputProps}
                    />
                </Form.Item>
            </Col>
        </Row>
    </Form.Item>
);
// 表单数据接口，基于SelectedSegmentInfo
interface TextStyleFormData extends SelectedSegmentInfo {
    // 继承SelectedSegmentInfo的所有字段
    textContent: TextContent;
}
const TextStyleForm: React.FC = () => {
    const [form] = Form.useForm();
    // 从Redux store获取选中的片段信息和素材数据
    const draft = useSelector((state: RootState) => state.drafts);
    const selectedSegment = useSelector(selectSelectedSegment);
    const materials = selectMaterials({ draft: draft });

    // 获取文本内容数据
    const textContent = useMemo(() => {

        if (!selectedSegment?.material_id) {
            return null;
        }

        if (!materials) {
            return null;
        }

        if (!materials.texts || !Array.isArray(materials.texts)) {
            return null;
        }

        // 从texts数组中过滤出对应素材ID的文本对象
        const textMaterial = materials.texts.find((text: TextContent) => text.id === selectedSegment.material_id);

        if (!textMaterial) {
            return null;
        }

        if (!textMaterial.content) {
            return null;
        }

        try {
            // 解析content JSON字符串
            const parsedContent: TextContent = JSON.parse(textMaterial.content);
            return parsedContent;
        } catch (error) {
            console.error('解析文本内容失败:', error);
            return null;
        }
    }, [selectedSegment?.material_id, materials]);


    // 处理值变化 - 只发送数据到事件总线，不立即保存
    const handleValuesChange = (changedValues: any, allValues: TextStyleFormData) => {

        // 只有在表单值真正发生变化时才发送事件
        // 避免在Tab切换或初始化时触发
        if (Object.keys(changedValues).length > 0) {
            const formData = {
                draftId: selectedSegment.draftId,
                trackId: selectedSegment.trackId,
                id: selectedSegment.id,
                material_id: selectedSegment.material_id,
                start: allValues.start,
                duration: allValues.duration,
                clip: allValues.clip,
                textContent: allValues.textContent,
            };
            // 发送表单数据到事件总线
            (eventBus as any).emit('form:data:changed', {
                segmentId: selectedSegment.id,
                formData: formData,
                formType: 'text',
            });
        }
    };

    // 初始化表单值
    useEffect(() => {
        if (selectedSegment) {
            // 合并selectedSegment和textContent数据
            const formData = {
                ...selectedSegment,
                textContent: textContent || '',
            };
            form.setFieldsValue(formData);
        } else {
            // 如果没有选中文本片段，重置表单
            form.resetFields();
        }
    }, [selectedSegment, textContent, form]);

    return (
        <GlobalDarkThemeStyle>
            <Form form={form} layout="vertical" autoComplete="off" onValuesChange={handleValuesChange}>
                {/* 文本内容与样式 */}
                {textContent && (
                    <Card title={<div style={{ color: '#FFFFFF' }}>文本内容与样式</div>} size="small" style={{ marginBottom: 16 }} className={'form-card'}>
                        <Form.Item label="文本内容" name={['textContent', 'text']}>
                            <Input.TextArea
                                style={{
                                    backgroundColor: '#2a2a2a',
                                    borderColor: '#434343',
                                    color: '#ffffff',
                                }}
                                value={textContent.text}
                                rows={3}
                                placeholder="文本内容"
                            />
                        </Form.Item>

                        {textContent.styles &&
                            textContent.styles.map((style, index) => (
                                <>
                                    {/* 基础文本属性 */}
                                    <Row gutter={16}>
                                        <Col span={6}>
                                            <Form.Item label="字体大小" name={['textContent', 'styles', 0, 'size']}>
                                                <InputNumber
                                                    value={style.size}
                                                    min={1}
                                                    max={200}
                                                    style={{
                                                        width: '100%',
                                                        backgroundColor: '#2a2a2a',
                                                        borderColor: '#434343',
                                                        color: '#ffffff',
                                                    }}
                                                />
                                            </Form.Item>
                                        </Col>
                                        <Col span={6}>
                                            <Form.Item label="粗体" name={['textContent', 'styles', index, 'bold']} valuePropName="checked">
                                                <Switch checked={style.bold} style={{ backgroundColor: '#555555' }} checkedChildren={<div style={{ color: '#ffffff' }}>✓</div>} />
                                            </Form.Item>
                                        </Col>
                                        <Col span={6}>
                                            <Form.Item label="斜体" name={['textContent', 'styles', index, 'italic']} valuePropName="checked">
                                                <Switch checked={style.italic} style={{ backgroundColor: '#555555' }} checkedChildren={<div style={{ color: '#ffffff' }}>✓</div>} />
                                            </Form.Item>
                                        </Col>
                                        <Col span={6}>
                                            <Form.Item label="下划线" name={['textContent', 'styles', index, 'underline']} valuePropName="checked">
                                                <Switch checked={style.underline} style={{ backgroundColor: '#555555' }} checkedChildren={<div style={{ color: '#ffffff' }}>✓</div>} />
                                            </Form.Item>
                                        </Col>
                                    </Row>

                                    {/* 填充配置 */}

                                    <Row gutter={20}>
                                        <Form.Item label="渲染类型" name={['textContent', 'styles', index, 'fill', 'content', 'render_type']} hidden={true}>
                                            <InputNumber
                                                value="solid"
                                                style={{
                                                    width: '100%',
                                                    backgroundColor: '#2a2a2a',
                                                    borderColor: '#434343',
                                                    color: '#ffffff',
                                                }}
                                                hidden={true}
                                            />
                                        </Form.Item>
                                    </Row>
                                    <Row gutter={20}>
                                        <Col span={24}>
                                            <Form.Item label="实体颜色">
                                                <Row gutter={20}>
                                                    <Col span={8}>
                                                        <Form.Item name={['textContent', 'styles', index, 'fill', 'content', 'solid', 'color', 0]} label="R通道">
                                                            <InputNumber
                                                                min={0}
                                                                max={1}
                                                                step={0.01}
                                                                style={{
                                                                    width: '100%',
                                                                    backgroundColor: '#2a2a2a',
                                                                    borderColor: '#434343',
                                                                    color: '#ffffff',
                                                                }}
                                                            />
                                                        </Form.Item>
                                                    </Col>
                                                    <Col span={8}>
                                                        <Form.Item name={['textContent', 'styles', index, 'fill', 'content', 'solid', 'color', 1]} label="G通道">
                                                            <InputNumber
                                                                min={0}
                                                                max={1}
                                                                step={0.01}
                                                                style={{
                                                                    width: '100%',
                                                                    backgroundColor: '#2a2a2a',
                                                                    borderColor: '#434343',
                                                                    color: '#ffffff',
                                                                }}
                                                            />
                                                        </Form.Item>
                                                    </Col>
                                                    <Col span={8}>
                                                        <Form.Item name={['textContent', 'styles', index, 'fill', 'content', 'solid', 'color', 2]} label="B通道">
                                                            <InputNumber
                                                                min={0}
                                                                max={1}
                                                                step={0.01}
                                                                style={{
                                                                    width: '100%',
                                                                    backgroundColor: '#2a2a2a',
                                                                    borderColor: '#434343',
                                                                    color: '#ffffff',
                                                                }}
                                                            />
                                                        </Form.Item>
                                                    </Col>
                                                </Row>
                                            </Form.Item>
                                        </Col>
                                        <Form.Item label="范围" name={['textContent', 'styles', index, 'range', 0]} hidden={true}>
                                            <InputNumber
                                                min={0}
                                                max={1}
                                                step={0.01}
                                                style={{
                                                    width: '100%',
                                                    backgroundColor: '#2a2a2a',
                                                    borderColor: '#434343',
                                                    color: '#ffffff',
                                                }}
                                            />
                                        </Form.Item>
                                        <Form.Item label="范围" name={['textContent', 'styles', index, 'range', 1]} hidden={true}>
                                            <InputNumber
                                                min={0}
                                                max={1}
                                                step={0.01}
                                                style={{
                                                    width: '100%',
                                                    backgroundColor: '#2a2a2a',
                                                    borderColor: '#434343',
                                                    color: '#ffffff',
                                                }}
                                            />
                                        </Form.Item>
                                    </Row>
                                </>
                            ))}
                    </Card>
                )}

                {/* 时间配置 */}
                <Card title={<div style={{ color: '#FFFFFF' }}>时间配置</div>} size="small" style={{ marginBottom: 16 }} className={'form-card'}>
                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item label="目标开始时间" name={['start']} rules={[{ required: true, message: '请输入开始时间' }]}>
                                <InputNumber
                                    min={0}
                                    placeholder="开始时间（微秒）"
                                    style={{
                                        width: '100%',
                                        backgroundColor: '#2a2a2a',
                                        borderColor: '#434343',
                                        color: '#ffffff',
                                    }}
                                />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item label="目标持续时间" name={['duration']} rules={[{ required: true, message: '请输入持续时间' }]}>
                                <InputNumber
                                    min={1}
                                    placeholder="持续时间（微秒）"
                                    style={{
                                        width: '100%',
                                        backgroundColor: '#2a2a2a',
                                        borderColor: '#434343',
                                        color: '#ffffff',
                                    }}
                                />
                            </Form.Item>
                        </Col>
                    </Row>
                </Card>

                {/* 裁剪设置 */}
                <Card title={<div style={{ color: '#FFFFFF' }}>裁剪设置</div>} size="small" style={{ marginBottom: 16 }} className={'form-card'}>
                    <SliderInputRow label="透明度" name={['clip', 'alpha']} sliderProps={{ min: 0, max: 1, step: 0.01 }} inputProps={{ min: 0, max: 1, step: 0.01 }} />

                    <SliderInputRow label="旋转角度" name={['clip', 'rotation']} sliderProps={{ min: -360, max: 360, step: 1 }} inputProps={{ min: -360, max: 360, step: 1 }} />

                    <SliderInputRow label="X轴缩放" name={['clip', 'scale', 'x']} sliderProps={{ min: 0, max: 3, step: 0.01 }} inputProps={{ min: 0, max: 3, step: 0.01 }} />

                    <SliderInputRow label="Y轴缩放" name={['clip', 'scale', 'y']} sliderProps={{ min: 0, max: 3, step: 0.01 }} inputProps={{ min: 0, max: 3, step: 0.01 }} />

                    <SliderInputRow label="X轴位置" name={['clip', 'transform', 'x']} sliderProps={{ min: -1, max: 1, step: 0.01 }} inputProps={{ min: -1, max: 1, step: 0.01 }} />

                    <SliderInputRow label="Y轴位置" name={['clip', 'transform', 'y']} sliderProps={{ min: -1, max: 1, step: 0.01 }} inputProps={{ min: -1, max: 1, step: 0.01 }} />

                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item label="水平翻转" name={['clip', 'flip', 'horizontal']} valuePropName="checked">
                                <Switch checkedChildren={<div style={{ color: '#ffffff' }}>开启</div>} unCheckedChildren={<div style={{ color: '#ffffff' }}>关闭</div>} style={{ backgroundColor: '#555555' }} />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item label="垂直翻转" name={['clip', 'flip', 'vertical']} valuePropName="checked">
                                <Switch checkedChildren={<div style={{ color: '#ffffff' }}>开启</div>} unCheckedChildren={<div style={{ color: '#ffffff' }}>关闭</div>} style={{ backgroundColor: '#555555' }} />
                            </Form.Item>
                        </Col>
                    </Row>
                </Card>
            </Form>
        </GlobalDarkThemeStyle>
    );
};

export default TextStyleForm;
export type { TextStyleFormData };
